import { NavBar, ProductCard, Stepper, Checkbox, SubmitBar, Sticky } from 'react-vant';
import { ArrowLeft, WeappNav } from '@react-vant/icons';
import TabBar from '../../components/TabBar'
import './index.css'
import { useEffect, useState, useMemo } from 'react';
import Taro from '@tarojs/taro';
import axios from 'axios';

export default function Cart() {
  // 提交订单
  const handleSubmit = () => {
    if (selectedCount === 0) {
      Taro.showToast({
        title: '请选择要购买的商品',
        icon: 'none'
      });
      return;
    }
    Taro.navigateTo({
      url: '/user/pages/payment/index'
    })
  }

  // 获取购物车商品
  const [cartGoodsList, setCartGoodsList] = useState<any>([])
  const getCartGoodsAPI = async () => {
    const { data } = await axios.get('http://localhost:3000/getCartGoods')
    setCartGoodsList(data.cartGoods)
  }

  // 计算选中商品的总价
  const totalPrice = useMemo(() => {
    return cartGoodsList
      .filter(item => item.isChecked)
      .reduce((total, item) => {
        return total + (item.goodsPrice * item.goodsNum);
      }, 0) * 100; // 转换为分单位，因为SubmitBar组件需要
  }, [cartGoodsList]);

  // 计算选中的商品数量
  const selectedCount = useMemo(() => {
    return cartGoodsList.filter(item => item.isChecked).length;
  }, [cartGoodsList]);

  useEffect(() => {
    getCartGoodsAPI()
  }, [])

  // 改变复选框状态
  const updateCartChecked = async (_id) => {
    await axios.put('http://localhost:3000/updateCartChecked', { _id });
    getCartGoodsAPI()
  }

  // 判断购物车是否全部选中
  const [allChecked, setAllChecked] = useState(false)
  useEffect(() => {
    const isAllChecked = cartGoodsList.length > 0 && cartGoodsList.every(item => item.isChecked);
    setAllChecked(isAllChecked);
  }, [cartGoodsList]);

  // 处理全部选中
  const handleAllChecked = async (checked) => {
    await axios.put('http://localhost:3000/updateCartCheckedBatch', {
      isChecked: checked
    });
    getCartGoodsAPI()
  }

  // 处理商品数量
  const handleGoodsNum = async (_id, num) => {
    await axios.put('http://localhost:3000/updateCartNum', {
      _id,
      num
    })
    getCartGoodsAPI()
  }

  return (
    <div className='cart-container'>
      <Sticky>
        <NavBar
          title="购物车"
          leftArrow={<ArrowLeft />}
          rightText={<WeappNav />}
        />
      </Sticky>
      <Sticky offsetTop={46}>
        <div className='cart-nav'>
          <span>购物车（{cartGoodsList.length}）</span>
        </div>
      </Sticky>

      {cartGoodsList.map((item, index) => {
        return <div key={index}>
          <div className='shop-name'>{item.shopName}</div>
          <div className='cart-card' >
          <Checkbox checkedColor='#ee0a24' checked={item.isChecked} onClick={() => updateCartChecked(item._id)}>
          </Checkbox>
          <ProductCard
            num={<Stepper
              min={1}
              value={item.goodsNum}
              onMinus={() => handleGoodsNum(item._id, -1)}
              onPlus={() => handleGoodsNum(item._id, 1)}
            />}
            price={item.goodsPrice}
            desc={item.goodsDes}
            title={item.goodsName}
            thumb={item.goodsImgsrc}
          />
        </div>
        </div>

      })}
      <div style={{ height: '100vh' }}></div>
      <Sticky position='bottom' offsetBottom={50}>
        <div className='cart-submit'>
          <SubmitBar
            price={totalPrice}
            buttonText="提交订单"
            onSubmit={handleSubmit}
          >
            <Checkbox onChange={handleAllChecked} checked={allChecked}>全选</Checkbox>
          </SubmitBar>
        </div>
      </Sticky>
      <TabBar />
    </div>
  )
}
